package com.wanlian.router.ui.main.yun;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.ImageView;

import com.github.chrisbanes.photoview.PhotoView;
import com.smart.android.image.ImageLoader;
import com.smart.android.ui.BaseActivity;
import com.smart.android.ui.app.IntentExtra;
import com.smart.android.utils.FileUtils;
import com.wanlian.router.R;
import com.wanlian.router.bean.FileType;
import com.wanlian.router.bean.YunFile;
import com.wanlian.router.event.RefreshEvent;
import com.wanlian.router.net.NetWorkingClient;
import com.wanlian.router.net.ResponseData;
import com.wanlian.router.net.file.listener.impl.UIProgressListener;
import com.wanlian.router.net.file.utils.OKHttpUtils;
import com.wanlian.router.net.internal.INetCallBack;

import org.greenrobot.eventbus.EventBus;

import java.io.File;

import butterknife.BindView;

/**
 * Created by Hyu on 2018/10/21.
 * Email: fvaryu@163.com
 */
public class PicturePreviewActivity extends BaseActivity {
    @BindView(R.id.image_picture)
    PhotoView image_picture;
    private ProgressDialog mProgressDialog;


    public static void go(Context context, YunFile file) {
        Intent intent = new Intent(context, PicturePreviewActivity.class);
        intent.putExtra(IntentExtra.EXTRA_OBJ, file);
        context.startActivity(intent);
    }


    @Override
    protected int layout() {
        return R.layout.activity_picture_preview;
    }


    @Override
    public void initUI() {
        super.initUI();
        setTitle("照片");
        setNextImage(R.drawable.more);
        setNextClickLisener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MoreDialog dialog = new MoreDialog(getActivity());
                dialog.setOnItemClickListener(new MoreDialog.OnItemClickListener() {
                    @Override
                    public void onItemClick(MoreDialog.Op op) {
                        YunFile file = (YunFile) getIntent().getSerializableExtra(IntentExtra.EXTRA_OBJ);
                        op(op, file);
                    }
                });
                dialog.setTitle("照片");
                dialog.show();
            }
        });
        image_picture.setMinimumScale(0.5f);
        image_picture.setMaximumScale(2.f);
    }

    @Override
    public void initData() {
        super.initData();
        YunFile file = (YunFile) getIntent().getSerializableExtra(IntentExtra.EXTRA_OBJ);
        ImageLoader.load(getActivity(), file.getFilePath(), image_picture);

    }

    private void op(final MoreDialog.Op op, final YunFile file) {
        switch (op.ordinal()) {
            case 0: {
                if (!FileUtils.isSDCardAvailable()) {
                    showToast("SDcard不可用，请检查");
                    return;
                }

                final String path = String.format("%s/%s", Environment.getExternalStorageDirectory().getAbsolutePath(), "wanlian/pictures");
                FileUtils.createDirs(path);


                File or = new File(path, file.getFileName());
                if (or.exists()) {
                    FileUtils.deleteFile(or.getAbsolutePath());
                }
//                String fileName = file.getFileName();
//                while (or.exists()) {
//                    if (file.getFileType() == FileType.Picture.ordinal()) {
//
//                    }
//                    String[] names = or.getName().substring(0, )
//                    fileName =
//                }

                final File save = FileUtils.createFile(path, file.getFileName());
                if (mProgressDialog == null) {
                    mProgressDialog = new ProgressDialog(getActivity());
                    mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                    mProgressDialog.setCancelable(false);
                    mProgressDialog.setCanceledOnTouchOutside(false);
                    mProgressDialog.setTitle("下载中...");
                    mProgressDialog.show();
                }

                OKHttpUtils.downloadAndSaveFile(this, file.getFilePath(), save.getAbsolutePath(), new UIProgressListener() {
                    @Override
                    public void onUIProgress(long currentBytes, long contentLength, boolean done) {
                        int progress = 0;
                        if (contentLength != 0) {
                            progress = (int) (currentBytes * 100.f / contentLength);
                        }
                        if (done) {
                            progress = 100;
                        }
                        mProgressDialog.setProgress(progress);

                        if (progress == 100) {
                            mProgressDialog.dismiss();
                            showToast("下载成功：" + path);

                            try {
                                sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(save)));
                            } catch (Exception e) {
                            }
                        }
                    }
                });
            }
            break;
            case 2: {
                InputDialog inputDialog = new InputDialog(getActivity());
                inputDialog.setOnNameInputListener(new InputDialog.OnNameInputListener() {
                    @Override
                    public void onNameInput(Dialog dialog, final String name) {
                        dialog.dismiss();
                        NetWorkingClient.getInstance().renameYunFile(getActivity(), name, file.getId(), new INetCallBack() {
                            @Override
                            public void onFinish(ResponseData response, @Nullable Object o) {
                                if (response.isSuccess()) {
                                    showToast("修改成功");
                                    EventBus.getDefault().post(new RefreshEvent(FileType.Picture));
                                } else {
                                    showToast(response.getMessage());
                                }
                            }
                        });
                    }
                });
                inputDialog.show();
            }
            break;
            case 1: {
                DeleteDialog deleteDialog = new DeleteDialog(getActivity());
                deleteDialog.setFileName(file.getFileName());
                deleteDialog.setOnClickListener(new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        NetWorkingClient.getInstance().delectYunFile(getActivity(), file.getId(), new INetCallBack() {
                            @Override
                            public void onFinish(ResponseData response, @Nullable Object o) {
                                if (response.isSuccess()) {
                                    showToast("删除成功");
                                    EventBus.getDefault().post(new RefreshEvent(FileType.Picture));

                                    finish();
                                } else {
                                    showToast(response.getMessage());
                                }
                            }
                        });
                    }
                });
                deleteDialog.show();

            }
            break;
            case 3: {
                Bundle bundle = new Bundle();
                bundle.putInt(IntentExtra.EXTRA_ID, file.getId());
                redirectActivity(YunFileDetailActivity.class, bundle);
            }
            break;
        }
    }
}
